﻿namespace BM.GUI
{

    using System.Windows.Forms;
    using BM.Common;
    using BM.Core;

    public partial class fConfig : Form
    {
        Agent _bmAgent;

        public fConfig()
        {
            try {
                Log.Write("Open Configuration");
                InitializeComponent();

                // true is bs Super changer
                // false is xChanger

                _bmAgent = new Agent(false);
                var bs = _bmAgent._bsConfig;
                var config = _bmAgent._bmConfig;

                _txtRepository.Text = config.BackUpBase;
                _rtbDataPaths.Text = config.DataPaths;

                // Hiển thị thông tin cấu hình Bluestack
                ulong memory = 0;
                var memStatus = new NativeMethods.MemoryStatusEX();
                if (NativeMethods.GLobalMemoryStatusExManaged(memStatus))
                    memory = memStatus.ullTotalPhys;

                // 1048576 = 1024 * 1024
                _lPhysicMemory.Text = string.Format("/{0}MB", (float) memory / 1048576);
                _nUDBSWidth.Value = bs.WindowWidth;
                _nUDBSHeight.Value = bs.WindowHeight;
                _nUDBSMemory.Value = bs.PhysicMemory;
            }
            catch {
                throw;
            }
        }

        /// <summary>
        /// Add file to data path
        /// </summary>        
        private void _btnAddFile_Click(object sender, System.EventArgs e)
        {
            var open = new OpenFileDialog() { Multiselect = true };
            if (DialogResult.OK == open.ShowDialog()) {
                for (int i = 0, len = open.FileNames.Length; i < len; i++) {
                    if (_rtbDataPaths.Text.Trim() != "")
                        _rtbDataPaths.Text += "|"; // Add | if rtbDataPath contain text
                    _rtbDataPaths.Text += open.FileNames[i];

                    Log.Write(open.FileNames[i] + " added to data paths");
                }
            }
        }

        /// <summary>
        /// Add folder to data path
        /// </summary>        
        private void _btnAddPath_Click(object sender, System.EventArgs e)
        {
            var fbd = new FolderBrowserDialog();
            if (DialogResult.OK == fbd.ShowDialog()) {
                if (_rtbDataPaths.Text.Trim() != "")
                    _rtbDataPaths.Text += "|";
                _rtbDataPaths.Text += fbd.SelectedPath;

                Log.Write(fbd.SelectedPath + " folder added to data paths");
            }
        }

        /// <summary>
        /// Change BlueStack size
        /// </summary>
        private void btnGetSize_Click(object sender, System.EventArgs e)
        {
            using (var blank = new fBlank()) {
                blank.ShowDialog();
                _nUDBSWidth.Value = System.Math.Abs(blank.x2 - blank.x1);
                _nUDBSHeight.Value = System.Math.Abs(blank.y2 - blank.y1);
            }
        }

        /// <summary>
        /// Close
        /// </summary>        
        private void btnCancel_Click(object sender, System.EventArgs e)
        {
            var cancel = MessageBox.Show("Are you sure you want to cancel?", "Cancel", MessageBoxButtons.YesNo);
            if (DialogResult.Yes == cancel) {
                Log.Write("Cancel config setting");
                this.Close();
            }
        }

        /// <summary>
        /// Save change
        /// </summary>
        private void btnOK_Click(object sender, System.EventArgs e)
        {
            try {

                var save = MessageBox.Show("Save change?", "Configuration Message", MessageBoxButtons.YesNo);
                if (save == DialogResult.Yes) {

                    // Set BlueStack config
                    _bmAgent._bsConfig.WindowHeight = (int) _nUDBSHeight.Value;
                    _bmAgent._bsConfig.WindowWidth = (int) _nUDBSWidth.Value;
                    _bmAgent._bsConfig.PhysicMemory = (int) _nUDBSMemory.Value;
                    BSConfig.SaveSetting(_bmAgent._bsConfig);

                    // Set BM
                    _bmAgent._bmConfig.BackUpBase = _txtRepository.Text;
                    _bmAgent._bmConfig.DataPaths = _rtbDataPaths.Text.Trim();
                    BMConfig.SaveSetting(_bmAgent._bmConfig);

                    Log.Write("Config saved.");
                    MessageBox.Show("Your configuration has been saved!", "ALERT", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    this.Close();
                }
            }
            catch (System.Exception ex) {
                MessageBox.Show(string.Concat("Error: ", ex.Message, "\nPlease report a bug for us."), "Configuration Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Log.Write("Exception when save config: " + ex.Message);
            }
        }

        /// <summary>
        /// Scan backup
        /// </summary>        
        private void _btnScanBackUp_Click(object sender, System.EventArgs e)
        {
            var folder = new FolderBrowserDialog();
            if (DialogResult.OK != folder.ShowDialog()) return;

            var backups = System.IO.Directory.GetDirectories(folder.SelectedPath);

            _bmAgent._bmConfig.BackUps.AddRange(backups);

            _clbBackUps.Items.Clear();
            _clbBackUps.Items.AddRange(_bmAgent._bmConfig.BackUps.ToArray());
        }

        /// <summary>
        /// Delete selected backup path
        /// </summary>
        private void _btnDeleteBackUp_Click(object sender, System.EventArgs e)
        {
            for (var i = _clbBackUps.Items.Count - 1; i > -1; --i) {
                if (!_clbBackUps.GetItemChecked(i)) continue;
                _bmAgent._bmConfig.BackUps.RemoveAt(i);
            }
            _clbBackUps.Items.Clear();
            _clbBackUps.Items.AddRange(_bmAgent._bmConfig.BackUps.ToArray());
        }

        /// <summary>
        /// Check all backup
        /// </summary>        
        private void _btnSelectAllBackUp_Click(object sender, System.EventArgs e)
        {
            for (var i = 0; i < _clbBackUps.Items.Count; ++i) {
                _clbBackUps.SetItemChecked(i, true);
            }
        }
    }
}
